<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\api\controller\user;

use app\api\controller\Controller;
use app\common\model\Position as PositionModel;
use app\common\model\User as UserModel;
use app\common\model\DeliveryImg as DeliveryImgModel;
use app\store\model\UploadFile;
use app\common\library\storage\Driver as StorageDriver;
use app\store\model\Setting as SettingModel;
use app\common\model\Myfav as MyfavModel;
use think\Db;

/**
 * Description of Delivery
 *  配送员接口
 * @author Administrator
 */
class Delivery extends Controller {
    /* @var \app\api\model\User $user */

    private $user;
    private $config;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function _initialize() {
        parent::_initialize();
        $this->user = $this->getUser();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
    }

    /**
     * 记录定位信息
     * @param type $longitude
     * @param type $latitude
     */
    public function addmap($longitude, $latitude, $status, $order_id) {

        $lngLat = $latitude . ',' . $longitude;
        $aData = [
            'key' => 'P5OBZ-VK43J-PUOFS-FAKLJ-CTJME-OVB3Y', //密匙
            'location' => $lngLat, //经纬度信息
        ];
        $url = 'https://apis.map.qq.com/ws/geocoder/v1/'; //获取详细地址信息

        $aMap = postCurl($url, $aData);
        $aArrMap = json_decode($aMap, true); //转化为数组
        if ($aArrMap['status']) {
            return $this->renderError($aArrMap['message']);
        }
        $maOrder = [
            'longitude' => $longitude, //纬度
            'latitude' => $latitude, //经度
            'user_id' => $this->user['user_id'], //配送员id
            'status' => $status, //配送员状态
            'create_time' => time(), //记录时间
            'add_text' => $aArrMap['result']['address'], //具体地址（从腾讯API接口获取）
            'order_id' => $order_id, //订单id
            'wxapp_id' => $this->user['wxapp_id'], //配送员id
        ];
        //根据配送员状态写入记录表
        switch ($status) {
            case 1:
                //写入轨迹表
                $aSave = (new PositionModel)->allowField(true)->save($maOrder);
                break;
            case 2:
                $where = ['wxapp_id' => $this->user['wxapp_id'], 'status' => 2, 'user_id' => $this->user['user_id']];
                $aIf = [];
                //更新用户表
                $aIf = (new PositionModel)->allowField(true)->get($where);
                if ($aIf) {
                    $aSave = (new PositionModel)->allowField(true)->save($maOrder, $where);
                } else {
                    $aSave = (new PositionModel)->allowField(true)->save($maOrder);
                }
                break;
            case 3:
                break;
            default:
                break;
        }
        return $this->renderSuccess(compact('userInfo', 'orderCount'));
    }

    /**
     * 获取配送员列表
     * @param type $limit 分页显示条数
     * @param type $page   第几页
     * @return type
     */
    public function getdelivery($limit, $page, $user_type, $search, $longitude, $latitude) {
        $lngLat = $latitude . ',' . $longitude;
        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $limit = 1;
        }
        if ($user_type) {
            $aWhere['a.user_type'] = $user_type;
        }
        if ($search) {
            $aWhere['a.nickName'] = ['like', '%' . $search . '%']; //搜索
        }
        $isdefault = 'Y';
        $orderid = 1;

        $list = (new UserModel)->alias('a')
            ->join('position v', 'a.user_id = v.user_id' and 'g.order_id = ' . $orderid, 'left')  //运动轨迹表
            ->join('myfav m', 'a.user_id = m.p_id', 'left')  //收藏表
            ->join('delivery_img g', 'a.user_id = g.user_id 'and 'g.isdefault = ' . $isdefault, 'left')  //收藏表
            ->where($aWhere)
            ->order('a.isonline,a.isworking,m.index')
            ->group('a.user_id')
            ->field('g.*,m.*,v.*,a.*')//,
            ->paginate($limit, false, ['page' => $page]);
        $aData = [];
        ///计算距离
        $url = 'https://apis.map.qq.com/ws/distance/v1/?parameters';
        $aDatas = [
            'mode' => 'driving', //行进方式 driving（驾车）、walking（步行）
            'key' => 'P5OBZ-VK43J-PUOFS-FAKLJ-CTJME-OVB3Y', //密匙
            'to' => $lngLat, //终点经纬度
        ];
        $from = '';
        if ($list) {
            $aData = $list->toArray();
            $age = date("y", time());

            foreach ($list as $key => $value) {
                $list[$key]['p_id'] = $value['user_id'];
                $list[$key]['age'] = $age - $value['year'];
                $list[$key]['user_img'] = $value['file_url'] . '/' . $value['file_name'];
                //调接口
                $from .= $value['latitude'] . ',' . $value['longitude'] . ';';
            }
            $aDatas['from'] = trim($from, ';');
            //请求接口
            $aMap = curl($url, $aDatas);
            //计算距离和时间
            $aMap = json_decode($aMap, true);
            if ($aMap['result']['elements']) {
                $aApi = $aMap['result']['elements'];
                foreach ($list as $key => $value) {
                    foreach ($aApi as $k => $v) {
                        if ($value['latitude'] == $v['from']['lat'] && $value['longitude'] == $v['from']['lng']) {
                            $list[$key]['space'] = $v['distance'];
                            $list[$key]['time'] = $v['duration'];
                        }
                    }
                }
            }
        }


        return $this->renderSuccess($list);
    }
    /**
     * 根据p_id获取配送员信息
     * @return type
     */
    public function getDeliveryByID() {
        $aGet = $this->request->get();
        $aWhere['a.user_id'] = $this->user['user_id']; //配送员id
        $list = (new UserModel)->get(['user_id' => $aGet['p_id'], 'user_type' => 2]);
        if ($list) {
            return $this->renderSuccess($list, '获取配送员信息成功');
        }
        return $this->renderError('该配送员不存在');
    }
    /**
     * 收藏配送员列表
     * @param type $limit 分页显示条数
     * @param type $page   第几页
     * @return type
     */
    public function getmyfav($limit, $page, $search, $p_id) {
        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $page = 1;
        }
        if ($search) {
            $aWhere['m.nickName'] = ['like', '%' . $search . '%']; //搜索
        }
        $aWhere['a.user_id'] = $p_id; //配送员id
        $list = (new MyfavModel)->alias('a')
            ->join('user m', 'm.user_id = a.p_id', 'left')  //收藏表
            ->join('delivery_img g', 'a.user_id = g.user_id', 'left')  //收藏表
            ->where($aWhere)
            ->order('a.index desc')
            ->group('a.p_id')
            ->paginate($limit, false, ['page' => $page]);
        $aData = [];
        if ($list) {
            $aData = $list->toArray();
        }

        return $this->renderSuccess($list);
    }

    /**
     * 收藏配送员
     * @param type $limit 分页显示条数
     * @param type $page   第几页
     * @return type
     */
    public function addmyfav() {
        $aPost = $this->request->post();
        $aWhere['a.user_id'] = $this->user['user_id']; //配送员id
        if ((new UserModel)->get(['user_id' => $aPost['p_id'], 'user_type' => 2])) {
            //排序
            if (empty($aPost['index'])) {
                $indexs = [];
                $indexs = (new MyfavModel)->get(['user_id' => $this->user['user_id']]);
                if (empty($indexs)) {
                    $aPost['index'] = 1;
                }
                $aPost['index'] = $indexs['index'] + 1;
            }
            $pUser = [
                'user_id' => $this->user['user_id'],
                'p_id' => $aPost['p_id'],
                'index' => $aPost['index'],
                'create_time' => time(),
                'wxapp_id' => $this->wxapp_id,
            ];
            if ((new MyfavModel)->get(['user_id' => $this->user['user_id'], 'p_id' => $aPost['p_id']])) {
                return $this->renderError('该配送员已收藏');
            }
            $aReturn = (new MyfavModel)->allowField(true)->save($pUser, false);
            if ($aReturn) {
                return $this->renderSuccess($aPost, '收藏成功');
            }
        }
        return $this->renderError('该配送员不存在');
    }

    /**
     * 配送员图片列表
     * @param type $limit 分页显示条数
     * @param type $page   第几页
     * @return type
     */
    public function getimglist($limit, $page, $p_id) {
        $aWhere = [];
        if ($limit < 1) {
            $limit = 10;
        }
        if ($page < 1) {
            $limit = 1;
        }
        $aWhere['a.user_id'] = $p_id;
        $aWhere['a.is_delete'] = 0;
        $list = (new DeliveryImgModel)->alias('a')
//            ->join('myfav m', 'a.user_id = m.p_id', 'left')  //收藏表
//            ->join('delivery_img g', 'a.user_id = g.user_id', 'left')  //收藏表
            ->where($aWhere)
            ->order(['create_time desc'])
//            ->group('a.user_id')
//                ->field('o.user_name,y.quantity as quantity_use ,v.*,v.docdate as docdates,f.pay_name,f.pay_type,a.*,s.shop_name as name,t.btext as name,p.user_name as audit_name')//,
            ->paginate($limit, false, ['page' => $page]);
        $aData = [];
        if ($list) {
            $aData = $list->toArray();
        }
        return $this->renderSuccess($list);
    }

    /**
     * 软删除配送员图片
     * @param type $fileIds
     * @return type
     */
    public function deletefiles($fileIds) {
        $model = new DeliveryImgModel;
        $model->allowField(true)->save(['is_delete' => 1], ['d_id' => ['in', $fileIds]]);
        return json(['code' => 1, 'msg' => '删除成功', 'data' => $fileIds]);
    }

    /**
     * 图片上传接口
     * @param int $group_id
     * @return array
     * @throws \think\Exception
     */
    public function uploadimg($group_id = -1, $isdefault) {
        // 实例化存储驱动
        $StorageDriver = new StorageDriver($this->config);
        // 上传图片
        if (!$StorageDriver->upload())
            return json(['code' => 0, 'msg' => '图片上传失败' . $StorageDriver->getError()]);
        // 图片上传路径
        $fileName = $StorageDriver->getFileName();
        // 图片信息
        $fileInfo = $StorageDriver->getFileInfo();
        // 添加文件库记录
        $uploadFile = $this->addUploadFile($group_id, $fileName, $fileInfo, 'image', $isdefault);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '图片上传成功', 'data' => $uploadFile]);
    }

    /**
     * 添加文件库上传记录   
     * @param $group_id
     * @param $fileName
     * @param $fileInfo
     * @param $fileType
     * @return UploadFile
     */
    public function addUploadFile($group_id, $fileName, $fileInfo, $fileType, $isdefault) {
        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]) ? $this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new DeliveryImgModel;
        $model->allowField(true)->save([
            'group_id' => $group_id > 0 ? (int) $group_id : 0, //'文件分组id',
            'storage' => $storage, //'存储方式',
            'file_url' => $fileUrl, //'存储域名',
            'file_name' => $fileName, //'文件路径',
            'file_size' => $fileInfo['size'], //'文件大小(字节)',
            'file_type' => $fileType, // '文件类型',
            'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
            'is_delete' => 0, // '软删除',
            'wxapp_id' => $this->user['wxapp_id'], //'小程序id',
            'create_time' => time(), //'创建时间',
            'isdefault' => $isdefault, // '是否为默认 Y默认  N非默认',
            'user_id' => $this->user['user_id']
        ]);
        return $model;
    }

    /**
     * 修改用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userupdate() {

        #--获取前端表单数据：
        $data = $this->request->post();
        $model = new UserModel;#halt($data);

        #-- 开启事务
        Db::startTrans();
        try {
            #-- 修改user表：
            $res = $model->allowField(true)->save($data, ['user_id' => $this->user['user_id']]);
            #-- 如果是申请成为服务员，修改 bartender 表：
            if (!empty($data['status']) && $data['status']==1) {
                if (Db::name("bartender")->where(["user_id"=>$this->user['user_id']])->find()){
                    $res = Db::name("bartender")->where(["user_id"=>$this->user['user_id']])->update(['level'=>1,'service_fee'=>0]);
                }else{
                    $res = Db::name("bartender")->insert(['user_id' => $this->user['user_id']]);
                }
            }
            Db::commit();
            return $this->renderSuccess($res);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->renderError("出错了，请联系管理员！错误信息：".$e->getMessage());
        }

    }

    /**
     * 修改用户在线状态
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function isworkingupdate() {
        $aPost = $this->request->post();
        $model = new UserModel;
        $update = [];
        $userId = 0;
        if (isset($aPost['isworking']) && !empty($aPost['isworking'])) {
            $update['isworking'] = $aPost['isworking'];
            $userId = $aPost['user_id'];
        }
        if (isset($aPost['isonline']) && !empty($aPost['isonline'])) {
            $update['isonline'] = $aPost['isonline'];
            $userId = $this->user['user_id'];
        }
        if (!$update) {
            return $this->renderError('没有修改参数！');
        }
        $da = $model->allowField(true)->save($update, ['user_id' => $userId]);
        return $this->renderSuccess($da);
    }

    /**
     * 修改用户信息
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function userdelivery() {

        return (new MyfavModel)->where(['user_id' => $this->user['user_id']])->count();

        $aPost = $this->request->post();

        $model = new UserModel;
        $update = [
            'nickName' => $aPost['nickName'],
            'avatarUrl' => $aPost['avatarUrl'],
            'gender' => $aPost['gender'],
            'country' => $aPost['country'],
            'province' => $aPost['province'],
            'city' => $aPost['city'],
            'signature' => $aPost['signature'],
            'horoscope' => $aPost['horoscope'],
            'birthday' => $aPost['birthday'],
            'phone' => $aPost['phone'],
            'year' => $aPost['year'],
            'month' => $aPost['month'],
            'day' => $aPost['day'],
        ];
        $da = $model->allowField(true)->save($update, ['user_id' => $this->user['user_id']]);
        return $this->renderSuccess($da);
    }

}
